package com.usb.serial.device;

import android.Manifest;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import android.os.Build;
import android.os.Bundle;

import android.telephony.TelephonyManager;
import android.util.Base64;

import android.util.Log;


import android.view.MotionEvent;
import android.view.View;

import android.widget.AdapterView;
import android.widget.ArrayAdapter;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;

import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;

import com.google.gson.Gson;
import com.usb.serial.device.javaBean.InfoBean;
import com.usb.serial.device.util.MyOkHttp;
import com.usb.serial.device.util.Permission;
import com.usb.serial.device.util.SnModelUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.net.Socket;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.HashMap;

import java.util.Locale;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

import static com.usb.serial.device.SerialUtils.ByteArrToHex;

public class MainActivity extends AppCompatActivity {
    String byteArrToHex = "";
    private SerialControl serialControl;
    private final static String submit = "http://192.168.1.139:8582/api/addCradData";
    private final static String url = "http://192.168.1.139:8582/api/appData";
    private final static String yanzheng = "http://192.168.1.139:8582/api/yanzheng";
    private EditText editText;
    private ProgressDialog progressDialog;
    private TimeChangedReceiver timeChangedReceiver;
    private int secondsPassed;
    private ImageView icHand;
    private ConstraintLayout cl;
    private Button btn_site_visit, btn_in, btn_out, btn_lunch, btn_meeting, btn_phone, btn_pto, btn_break, ok;
    private TextView ll_text_birthDate1, nam1, sex1, ll_text_passportNo, ll_text_company, ll_text_department, ll_text_cardId, tvTime, tvDate;
    private final Gson gson = new Gson();
    private static final int REQUEST_READ_PHONE_STATE = 1;
    private InfoBean infoBean;
    private String stateId, imei1, state;
    private Socket socket;
    private String result;
    private Request request;
    private OkHttpClient client;
    private WebSocket ws;
    private CheckBox isFire;
    private Boolean flag = false;
    private Boolean flag1 = false;
    private boolean abc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(R.layout.activity_main/*mBinding.getRoot()*/);
        timeChangedReceiver = new TimeChangedReceiver();


        boolean grantExternalRW = Permission.isGrantExternalRW(this, 1);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查运行时权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // 没有权限，请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, REQUEST_READ_PHONE_STATE);
            } else {
                // 已经有权限，直接获取IMEI号码
                getIMEI();
            }
        } else {
            // Android版本低于6.0，直接获取IMEI号码
            getIMEI();
        }



        //初始化操作
        initView();
        initSocket();

        initSerialHelper();

        //初始化广播监听
//        initReceiver();

        //处理事件
        setOnClickListener();


    }

    private void initSocket() {

        socketConnect();

    }


    private void socketConnect() {


        Request request = new Request.Builder().url("ws://192.168.1.139:8582/api/websocket").build();
        client = new OkHttpClient();
        ws = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                // 连接成功
                Log.d("xxx", "成功了吗");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                // 接收文本消息
                Log.d("xxx", "text: " + text);
                if ("300".equals(text)) {
                    runOnUiThread(() -> {
                        editText.setVisibility(View.VISIBLE);
                        isFire.setVisibility(View.VISIBLE);
                    });
                }else {
                    runOnUiThread(() -> {
                        editText.setVisibility(View.GONE);
                        isFire.setVisibility(View.GONE);
                    });
                }

            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                // 接收二进制消息
                Log.d("xxx", "text: " + bytes);

            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                // 关闭连接中
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                // 连接关闭
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                Log.d("xxx", "onFailure: ");
                ws = client.newWebSocket(request, this);
            }
        });


    }


    private void getIMEI() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    String imei1 = telephonyManager.getImei(0); // 获取SIM卡槽1的IMEI号码
                } else {
                    imei1 = SnModelUtil.xx(this);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_PHONE_STATE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 获取权限成功
                getIMEI();
            } else {
            }
        }
    }


    private void setData(InfoBean infoBean) {
        nam1.setText(infoBean.getName());
        sex1.setText(infoBean.getGender());
        ll_text_passportNo.setText(infoBean.getNo());
        ll_text_company.setText(infoBean.getCompany());
        ll_text_department.setText(infoBean.getDepar());
        ll_text_cardId.setText(infoBean.getId());
        ll_text_birthDate1.setText(infoBean.getWarehousename());
        cl.setVisibility(View.GONE);
        byte[] imageBytes = Base64.decode(infoBean.getImage(), Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
        icHand.setImageBitmap(bitmap);
        canDialog();
    }

    private void cleanData() {
        nam1.setText("");
        sex1.setText("");
        ll_text_passportNo.setText("");
        ll_text_company.setText("");
        ll_text_department.setText("");
        ll_text_cardId.setText("");
        ll_text_birthDate1.setText("");
        editText.setText("");
    }


    private void setOnClickListener() {


        isFire.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {

                    if (!abc) {

                        // 在这里处理自定义的点击事件
                        // 在这里处理选中状态改变事件
                        // 创建AlertDialog.Builder对象
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("输入框弹窗");

                        // 创建一个 EditText 控件，并设置到弹窗中
                        final EditText input = new EditText(MainActivity.this);
                        builder.setView(input);

                        // 设置弹窗的确定按钮
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 在这里处理用户点击确定按钮后的逻辑
                                String password = input.getText().toString();

                                if (password.isEmpty()) {
                                    runOnUiThread(() -> {   Toast.makeText(MainActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();});
                                    return;
                                }

                                    Map<String, String> map = new HashMap<>();
                                    map.put("key", password);
                                    MyOkHttp.getInstance().post(yanzheng, map, new MyOkHttp.requestMessage() {
                                        @Override
                                        public void requestFail() {
                                            runOnUiThread(() -> {   Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();});
                                        }

                                        @Override
                                        public void requestComplete() {

                                        }

                                        @Override
                                        public void requestSuccess(Response response) throws IOException {
                                            String result = response.body().string();
                                            try {
                                                JSONObject js = new JSONObject(result);
                                                String code = js.getString("code");
                                                if ("200".equals(code)) {
                                                    runOnUiThread(() -> {
                                                        isFire.setChecked(true);
                                                        flag = true;
                                                    });
                                                }else {
                                                    runOnUiThread(() -> {   Toast.makeText(MainActivity.this, "对不起您的密码有误", Toast.LENGTH_SHORT).show();});
                                                    return;
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });


//                                if (password.equals("123456")) {
//                                    // 处理用户输入的内容
//                                    isFire.setChecked(true);
//                                    flag = true;
//                                } else {
//                                    Toast.makeText(MainActivity.this, "对不起您的密码有误", Toast.LENGTH_SHORT).show();
//                                }


                                Log.d("xxaaaa", "flag: " + flag);
                            }
                        });

                        // 设置弹窗的取消按钮
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 在这里处理用户点击取消按钮后的逻辑
                                isFire.setChecked(false);
                                flag = false;
                                dialog.cancel();  // 关闭弹窗
                            }
                        });

                        // 创建并显示弹窗
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    } else {
                        isFire.setChecked(false);
                    }
                    // 返回 true 表示事件已经被消费，不会继续执行默认的点击事件
                    return true;
                }
                // 返回 false 表示继续执行默认的点击事件
                return false;
            }
        });


        isFire.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                abc = isChecked;


            }
        });

    }


    //提交方法，走接口
    private void submit() {

        Log.d("jjjjj", "stateId: " + stateId);
        Map<String, String> map = new HashMap<>();
        map.put("warehouseCode", infoBean.getWarehouseCode());
        map.put("status", stateId == null ? "" : stateId);
        map.put("idNo", byteArrToHex);
        map.put("sncode", imei1);

        MyOkHttp.getInstance().post(submit, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "Server connection failure", Toast.LENGTH_SHORT).show();
                });

                canDialog();
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                runOnUiThread(() -> {
                    cl.setVisibility(View.VISIBLE);
                    canDialog();
                    cleanData();
                });
            }
        });

    }


    private void initView() {
        setTitle("门禁");
        String[] data = {"Apple", "Banana", "Cherry", "Durian", "Eggplant", "Fig", "Apple", "Banana", "Cherry", "Durian", "Eggplant", "Fig"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, data);
        editText = findViewById(R.id.auto_text_view);

        ok = findViewById(R.id.ok);

        cl = findViewById(R.id.go_image);

        nam1 = findViewById(R.id.ll_text_name);
        sex1 = findViewById(R.id.ll_text_sex);
        ll_text_passportNo = findViewById(R.id.ll_text_passportNo);
        ll_text_company = findViewById(R.id.ll_text_company);
        ll_text_department = findViewById(R.id.ll_text_department);
        ll_text_cardId = findViewById(R.id.ll_text_CardId);
        ll_text_birthDate1 = findViewById(R.id.ll_text_birthDate);
        icHand = findViewById(R.id.imageView);

        isFire = findViewById(R.id.is_fire);

        tvDate = findViewById(R.id.tv_date);
        tvTime = findViewById(R.id.tv_time);

        new Thread(() -> {
            //开一个定时任务
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 更新UI需要在主线程进行
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            secondsPassed++;
//                        String timeString = String.format("%d seconds passed", secondsPassed);
                            tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()));
                            tvDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                        }
                    });
                }
            }, 0, 1000); // 在0ms后开始执行任务，每隔1000ms执行一次
        }).start();


        tvDate.setText(new SimpleDateFormat("yyyy-MM-d").format(new Date()));
        tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()));
    }

    private void showPopupWindowNew(View v) {
        runOnUiThread(() -> {
            Dialog dialog = new Dialog(this);
            dialog.setContentView(R.layout.dialog_windows2);


            String[] data = new String[infoBean.getStatus().size()];
            for (int i = 0; i < infoBean.getStatus().size(); i++) {
                data[i] = infoBean.getStatus().get(i).getName();
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, data);
            Spinner spinner = dialog.findViewById(R.id.sp);

            spinner.setAdapter(adapter);
            Button b1 = dialog.findViewById(R.id.ok);
            Button b2 = dialog.findViewById(R.id.no);
            spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    state = infoBean.getStatus().get(position).getName();
                    stateId = infoBean.getStatus().get(position).getId();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            b1.setOnClickListener(view -> {
                submit();
                dialog.dismiss();
            });

            b2.setOnClickListener(view -> {
                dialog.dismiss();
            });


            dialog.show();

        });
    }

    private void showPopupWindow(View v) {
        runOnUiThread(() -> {
            Dialog dialog = new Dialog(this);
            dialog.setContentView(R.layout.dialog_windows);

            btn_in = dialog.findViewById(R.id.btn_in);
            btn_out = dialog.findViewById(R.id.btn_out);
            btn_lunch = dialog.findViewById(R.id.btn_lunch);
            btn_meeting = dialog.findViewById(R.id.btn_meeting);
            btn_phone = dialog.findViewById(R.id.btn_phone);
            btn_pto = dialog.findViewById(R.id.btn_pto);
            btn_break = dialog.findViewById(R.id.btn_break);
            btn_site_visit = dialog.findViewById(R.id.btn_SITE_VISIT);


            btn_in.setOnClickListener(view -> {
                editText.setText(btn_in.getText().toString().trim());
                dialog.dismiss();
            });
            btn_out.setOnClickListener(view -> {
                editText.setText(btn_out.getText().toString().trim());
                dialog.dismiss();
            });
            btn_lunch.setOnClickListener(view -> {
                editText.setText(btn_lunch.getText().toString().trim());
                dialog.dismiss();
            });
            btn_meeting.setOnClickListener(view -> {
                editText.setText(btn_meeting.getText().toString().trim());
                dialog.dismiss();
            });
            btn_phone.setOnClickListener(view -> {
                editText.setText(btn_phone.getText().toString().trim());
                dialog.dismiss();
            });
            btn_pto.setOnClickListener(view -> {
                editText.setText(btn_pto.getText().toString().trim());
                dialog.dismiss();
            });
            btn_break.setOnClickListener(view -> {
                editText.setText(btn_break.getText().toString().trim());
                dialog.dismiss();
            });
            btn_site_visit.setOnClickListener(view -> {
                editText.setText(btn_site_visit.getText().toString().trim());
                dialog.dismiss();
            });

            dialog.show();

        });
    }

    private void post(String carId) {
        showDialog("Loading...");
        Map<String, String> map = new HashMap<>();
        map.put("idNo", carId);
        map.put("sncode", imei1);
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {

            @Override
            public void requestFail() {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "Server connection failure", Toast.LENGTH_SHORT).show();
                    canDialog();
                });

            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                String result = response.body().string();
                if (result.isEmpty()) {
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this, "Unable to find this person", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    infoBean = gson.fromJson(result, InfoBean.class);
                    runOnUiThread(() -> {

                        setData(infoBean);

                        if (abc) {
                            submit();
                        } else {
                            showPopupWindowNew(ll_text_department);
                        }


                    });

                }
            }
        });
    }


    /**
     * 加载进度弹窗
     *
     * @param title 弹窗标题
     */
    public void showDialog(String title) {
        runOnUiThread(() -> {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(this);
            }
            if (progressDialog.isShowing()) {
                return;
            }
            progressDialog.setTitle(title);
            progressDialog.setMessage("Loading...");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        });
    }


    public void canDialog() {
        if (progressDialog != null) {
            runOnUiThread(() -> progressDialog.cancel());
        }
    }


    // 定义 BroadcastReceiver 类
    private class TimeChangedReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                // 获取当前时间
                String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

                String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());

                // 更新 TextView 的文本
                tvTime.setText(currentTime);
                tvDate.setText(currentDate);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        serialControl.close();
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        unregisterReceiver(timeChangedReceiver);
    }


    public void initSerialHelper() {
        serialControl = new SerialControl();
        initRead();
    }

    class SerialControl extends SerialHelper {

        @Override
        protected void onDataReceived(final ComBean comBean) {

            runOnUiThread(new Runnable() {
                public void run() {
                    DispRecData(comBean);
                }
            });

        }


    }

    StringBuilder sMsg;

    private void DispRecData(SerialHelper.ComBean ComRecData) {

        if (sMsg == null) {
            sMsg = new StringBuilder();
        }
        byte[] bytes = ComRecData.bytes;

        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));  // 将每个字节转换为两位的十六进制字符串
        }
        String hexString = sb.toString();  // 获取十六进制字符串
        BigInteger decimal = new BigInteger(hexString, 16);  // 将十六进制字符串转换为十进制数值
        sMsg.setLength(0);
        sMsg.append(byteArrToHex);
        byteArrToHex = String.valueOf(decimal);
        MyEquals(byteArrToHex);


    }

    private void MyEquals(String sMsg) {
        post(sMsg);
    }

    private void initRead() {


        serialControl.setPort("/dev/ttyUSB0");
        serialControl.setBaudRate("38400");
        File file = new File("/dev/ttyUSB0");
        try {
            serialControl.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!file.canRead() || !file.canWrite()) {
            return;
        }

    }

}
